import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {
    cancelOrder as cancelOrderApi,
    deliverOrder as deliverOrderApi,
    getOrderDetail as getOrderDetailApi,
    getOrderList as getOrderListApi,
    updateOrderRemark as updateOrderRemarkApi
} from '@/api/order'

/**
 * 订单管理Store
 * 管理订单列表、订单详情、订单状态等数据
 */
export const useOrderStore = defineStore('order', () => {
    // 状态
    const orders = ref([])
    const currentOrder = ref(null)
    const orderStatistics = ref(null)
    const loading = ref(false)
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)

    // 订单状态映射
    const orderStatusMap = {
        0: {text: '已取消', type: 'danger'},
        1: {text: '待支付', type: 'warning'},
        2: {text: '待发货', type: 'primary'},
        3: {text: '待收货', type: 'info'},
        4: {text: '已完成', type: 'success'},
        5: {text: '已过期', type: 'danger'}
    }

    // 支付状态映射
    const paymentStatusMap = {
        0: {text: '未支付', type: 'warning'},
        1: {text: '已支付', type: 'success'}
    }

    // 发货状态映射
    const deliveryStatusMap = {
        0: {text: '未发货', type: 'warning'},
        1: {text: '已发货', type: 'primary'},
        2: {text: '已收货', type: 'success'}
    }

    // 计算属性
    const orderCount = computed(() => orders.value.length)
    const hasOrders = computed(() => orders.value.length > 0)

    /**
     * 获取订单列表
     * @param {Object} params 查询参数
     */
    const getOrderList = async (params = {}) => {
        loading.value = true
        try {
            const response = await getOrderListApi({
                current: currentPage.value,
                size: pageSize.value,
                ...params
            })

            if (response.data) {
                orders.value = response.data.records || []
                total.value = response.data.total || 0
                currentPage.value = response.data.current || 1
            }

            return response
        } catch (error) {
            console.error('获取订单列表失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 获取订单详情
     * @param {number} id 订单ID
     */
    const getOrderDetail = async (id) => {
        console.log('开始获取订单详情, ID:', id)
        loading.value = true
        // 清空当前订单数据
        currentOrder.value = null
        try {
            const response = await getOrderDetailApi(id)
            console.log('订单详情API响应:', response)
            if (response.data) {
                currentOrder.value = response.data
                console.log('订单详情设置成功:', response.data)
            }
            return response
        } catch (error) {
            console.error('获取订单详情失败:', error)
            currentOrder.value = null
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 订单发货
     * @param {number} id 订单ID
     * @param {Object} deliveryData 发货数据
     */
    const deliverOrder = async (id, deliveryData) => {
        loading.value = true
        try {
            const response = await deliverOrderApi(id, deliveryData)
            // 发货成功后刷新列表
            await getOrderList()
            return response
        } catch (error) {
            console.error('订单发货失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 取消订单
     * @param {number} id 订单ID
     * @param {Object} cancelData 取消数据
     */
    const cancelOrder = async (id, cancelData) => {
        loading.value = true
        try {
            const response = await cancelOrderApi(id, cancelData)
            // 取消成功后刷新列表
            await getOrderList()
            return response
        } catch (error) {
            console.error('取消订单失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 更新订单备注
     * @param {number} id 订单ID
     * @param {Object} remarkData 备注数据
     */
    const updateOrderRemark = async (id, remarkData) => {
        loading.value = true
        try {
            const response = await updateOrderRemarkApi(id, remarkData)
            // 更新成功后刷新列表
            await getOrderList()
            return response
        } catch (error) {
            console.error('更新订单备注失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 更新订单状态
     * @param {number} id 订单ID
     * @param {Object} statusData 状态数据
     */
    const updateOrderStatus = async (id, statusData) => {
        loading.value = true
        try {
            const response = await request.put(`/admin/orders/${id}/status`, statusData)
            // 更新成功后刷新列表
            await getOrderList()
            return response
        } catch (error) {
            console.error('更新订单状态失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 获取订单统计信息
     * @param {string} startDate 开始日期
     * @param {string} endDate 结束日期
     */
    const getOrderStatistics = async (startDate, endDate) => {
        loading.value = true
        try {
            const params = {}
            if (startDate) params.startDate = startDate
            if (endDate) params.endDate = endDate

            const response = await request.get('/admin/orders/statistics', {params})
            if (response.data) {
                orderStatistics.value = response.data
            }
            return response
        } catch (error) {
            console.error('获取订单统计失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 设置分页参数
     * @param {number} page 页码
     * @param {number} size 每页大小
     */
    const setPagination = (page, size) => {
        currentPage.value = page
        pageSize.value = size
    }

    /**
     * 获取订单状态显示信息
     * @param {number} status 状态值
     */
    const getOrderStatusInfo = (status) => {
        return orderStatusMap[status] || {text: '未知', type: 'info'}
    }

    /**
     * 获取支付状态显示信息
     * @param {number} status 状态值
     */
    const getPaymentStatusInfo = (status) => {
        return paymentStatusMap[status] || {text: '未知', type: 'info'}
    }

    /**
     * 获取发货状态显示信息
     * @param {number} status 状态值
     */
    const getDeliveryStatusInfo = (status) => {
        return deliveryStatusMap[status] || {text: '未知', type: 'info'}
    }

    /**
     * 重置状态
     */
    const resetState = () => {
        orders.value = []
        currentOrder.value = null
        orderStatistics.value = null
        loading.value = false
        total.value = 0
        currentPage.value = 1
        pageSize.value = 10
    }

    return {
        // 状态
        orders,
        currentOrder,
        orderStatistics,
        loading,
        total,
        currentPage,
        pageSize,

        // 计算属性
        orderCount,
        hasOrders,

        // 方法
        getOrderList,
        getOrderDetail,
        deliverOrder,
        cancelOrder,
        updateOrderRemark,
        updateOrderStatus,
        getOrderStatistics,
        setPagination,
        getOrderStatusInfo,
        getPaymentStatusInfo,
        getDeliveryStatusInfo,
        resetState
    }
})
